from django.conf import settings
from django.core import mail
from itsdangerous.url_safe import URLSafeSerializer
from django.contrib.auth.backends import ModelBackend
import re
from  user.models import User
def send_email(to_email,subject,msg):
    mail.send_mail(subject=subject,
                   message='',
                   html_message=msg,
                   from_email=settings.EMAIL_HOST_USER,
                   recipient_list=[to_email]
                   )

def set_token(data):
    '''加密
    :param data: 需要加密的变量
    :return: 加密后的变量
    '''
    s = URLSafeSerializer(secret_key=settings.SECRET_KEY,salt='active')
    token = s.dumps(data)
    return token

def get_token(token):
    '''
    解密
    :param token:
    :return:
    '''
    s = URLSafeSerializer(secret_key=settings.SECRET_KEY, salt='active')
    data = s.loads(token)
    return data

def get_user_by_account(account):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user
class UsernameMobileModelBackend(ModelBackend):
    # 自己定义一个后端的类，重写authenticate方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None